package com.dating.pref;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Function {
	public static final String TAG = "class: Function";

	// require READ_PHONE_STATE
	public static String getDeviceId(Activity mActivity) {
		TelephonyManager tManager = (TelephonyManager) mActivity
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tManager.getDeviceId();
	}

	// get last geopoint
	public static Location getLastGeopoint(Context c)throws NullPointerException{
		LocationManager lm = (LocationManager) c
				.getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = lm.getProviders(true);

		/*
		 * Loop over the array backwards, and if you get an accurate location,
		 * then break out the loop
		 */
		Location l = null;

		for (int i = providers.size() - 1; i >= 0; i--) {
			l = lm.getLastKnownLocation(providers.get(i));
			if (l != null)
				break;
		}
		return l;
		/*
		 * try{ LocationManager manager_;
		 * 
		 * manager_ = (LocationManager)
		 * c.getSystemService(Context.LOCATION_SERVICE);
		 * 
		 * Location last =
		 * manager_.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		 * Log.e("location", last.getLatitude()+""); GeoPoint g=new
		 * GeoPoint(Integer.parseInt(last.getLatitude()*10E6+""),
		 * Integer.parseInt(last.getLongitude()*10E6+"")); return g;
		 * }catch(NullPointerException e){ e.printStackTrace(); return new
		 * GeoPoint(0, 0); }
		 */
	}
	public static String getAddressFromGeopoint(Context context,int lat, int lon) throws IOException {
		Geocoder geocoder;
		List<Address> addresses;
		geocoder = new Geocoder(context, Locale.getDefault());
		addresses = geocoder.getFromLocation(lat, lon, 1);

		String address = addresses.get(0).getAddressLine(0);
		String city = addresses.get(0).getAddressLine(1);
		String country = addresses.get(0).getAddressLine(2);
		return address + city + country;
	}
	public static Bitmap getImage(Context ctx, String external) {
		Bitmap bmp = null;

		return bmp;
	}

	/*--------------------------BITMAP IMAGE--------------------------*/
	public static Bitmap getBitmapFromUrl(URL url){
		Bitmap bitmap = null;
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new BufferedInputStream(url.openStream(), 4 * 1024);

			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			out = new BufferedOutputStream(dataStream, 4 * 1024);
			copy(in, out);
			out.flush();

			final byte[] data = dataStream.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			// Log.e(LOG_TAG, "bitmap returning something");
			return bitmap;
		}catch(MalformedURLException e){
			Log.e("get bitmap", e.getMessage());
		}
		catch (IOException e) {
			 Log.e("get bitmap", e.getMessage());
		}
		finally {
			closeStream(in);
			closeStream(out);
		}
		// Log.e(LOG_TAG, "bitmap returning null");
		return null;
	}

	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[4 * 1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				// Log.e(LOG_TAG, e.getMessage());
			}
		}
	}

	/*---------------  
	Get the image from the gallery
	----------------*/
	// launch the gallery to retrieve an image
	public static void getImageFromGallery(Activity atv) {
		Intent galleryIntent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
		atv.startActivityForResult(galleryIntent, Constant.GALLERY_PIC_REQUEST);
	}

	/*---------------  
	Get the image from the camera
	----------------*/
	public static void getImageFromCamera(Activity atv) {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		atv.startActivityForResult(intent, Constant.CAMERA_PIC_REQUEST);
	}

	public static void uploadImg(Bitmap bmp, String path) {
		if (bmp != null) {

		} else if (path != null && path != "") {

		}
	}

	/*--------------Generate MD5----------------*/
	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}
	/**
	 * generic String to MD5
	 * */
	public static String MD5(String text) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		MessageDigest md;
		md = MessageDigest.getInstance("MD5");
		byte[] md5hash = new byte[32];
		md.update(text.getBytes("iso-8859-1"), 0, text.length());
		md5hash = md.digest();
		return convertToHex(md5hash);
	}
	public static String toMD5(String fromTxt){
		try {
			return Function.MD5(fromTxt);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "error";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "error";
		}
	}
	@SuppressWarnings("unchecked")
	public static <T> T[] concat(T[] a, T[] b) {
		final int alen = a.length;
		final int blen = b.length;
		if (alen == 0) {
			return b;
		}
		if (blen == 0) {
			return a;
		}
		final T[] result = (T[]) java.lang.reflect.Array.newInstance(a
				.getClass().getComponentType(), alen + blen);
		System.arraycopy(a, 0, result, 0, alen);
		System.arraycopy(b, 0, result, alen, blen);
		return result;
	}
	public static String getPhoneNumber(Context context){
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getLine1Number();

	}
}
